<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="filters">
        <el-form-item>
          <el-input v-model="keyword" placeholder="关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="search">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="warning" @click="onsale">上架</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="warning" @click="offsale">下架</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表
       @selection-change="selsChange" 选的不一样就会触发
    -->
    <el-table :data="products" highlight-current-row v-loading="listLoading" @selection-change="selsChange"
              style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="name" label="名称" width="160" sortable>
      </el-table-column>
      <el-table-column prop="saleprice" label="售价" width="60" sortable>
      </el-table-column>
      <el-table-column prop="onsaletime" label="上架时间" width="160" sortable>
      </el-table-column>
      <el-table-column prop="offsaletime" label="下架时间" width="160" sortable>
      </el-table-column>
      <el-table-column prop="costprice" label="成本价" width="60" sortable>
      </el-table-column>
      <el-table-column prop="createtime" label="创建时间" width="160" sortable>
      </el-table-column>
      <el-table-column prop="salecount" label="销售数量" width="160" sortable>
      </el-table-column>
      <!--:formatter="formatState"-->
      <el-table-column prop="state" label="状态" width="150" sortable>
        <template scope="scope">
          <span style="color: red" v-if="scope.row.state==0">下架</span>
          <span style="color: green" v-else-if="scope.row.state==1">上架</span>
          <span style="color: darkblue" v-else>未知</span>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <!--如果没有选中就不能使用:disabled="this.sels.length===0"-->
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination layout="prev, pager, next" :current-page="currentPage" @current-change="handleCurrentChange"
                     :page-size="pageSize" :total="totals" style="float:right;">
      </el-pagination>
    </el-col>

    <!--新增或编辑界面-->
    <el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <!--:model="saveForm 模型绑定-->
      <!--:rules="saveFormRules" 校验规则-->
      <!--ref="saveForm" 给该表单定义一个引用名-->
      <el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
        <el-form-item label="名称" prop="name">
          <el-input v-model="saveForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="售价" prop="saleprice">
          <el-input v-model="saveForm.saleprice" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="成本价" prop="costprice">
          <el-input v-model="saveForm.costprice" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="资源" prop="resources">
          <el-upload class="upload-demo"
                     action="http://localhost:8080/fastdfs"
                     :on-remove="handleRemove"
                     :on-success="handleSuccess"
                     :file-list="fileList"
                     list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="saveForm.state">
            <el-radio class="radio" :label="0">下架</el-radio>
            <el-radio class="radio" :label="1">上架</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="简介" prop="intro">
          <!-- v-if="saveForm.petDetail" 修改v-model绑定对象报错问题，v-if对需要显示的数据判断下 -->
          <quill-editor  v-model="saveForm.productDetail.intro" v-if="saveForm.productDetail" :options="quillOption">
          </quill-editor>
        </el-form-item>
        <el-form-item label="预约须知" prop="orderNotice">
          <!-- v-if="saveForm.petDetail" 修改v-model绑定对象报错问题，v-if对需要显示的数据判断下 -->
          <quill-editor  v-model="saveForm.productDetail.orderNotice" v-if="saveForm.productDetail" :options="quillOption">
          </quill-editor>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="save" :loading="productLoading">提交</el-button>
      </div>
    </el-dialog>

  </section>
</template>

<script>
import {quillEditor} from "vue-quill-editor";
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
import quillConfig from '../../common/js/quill-config';

export default {
  components: {
    quillEditor
  },
  data() {
    return {
        keyword: '',
      quillOption: quillConfig,
      fileList: [],
      products: [],
      totals: 0,
      currentPage: 1,
      pageSize: 10,
      listLoading: false,
      sels: [],//列表选中列

      saveFormVisible: false,//新增界面是否显示
      productLoading: false,
      saveFormRules: {
        name: [
          {required: true, message: '请输入名称', trigger: 'blur'}
        ],
        costprice: [
          {required: true, message: '请输入售价', trigger: 'blur'}
        ],
        saleprice: [
          {required: true, message: '请输入成本价', trigger: 'blur'}
        ]
      },
      title: "",
      saveForm: {
        id: null,
        name: '',
        state: 0,
        resources: null,
        saleprice: 0,
        costprice: 0,
        productDetail:{  //与后端实体类一致
          intro: '',
          orderNotice: ''
        }
      },
    }
  },
  methods: {
    // //状态显示转换-不能上色
    // formatState: function (row, column) {
    // 	return row.state == 0 ? '正常' : row.state == -1 ? '禁用' : '未知';
    // },
    search() {
      //查询完，原来分页条件已经没用了，要跑到第一页去
      this.page = 1;
      this.getProducts();
    }
    ,
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getProducts();
    },
    //获取服务列表
    getProducts() {
      let para = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        keyword: this.keyword
      };
      this.listLoading = true;
      this.$http.post("/product", para)
          .then(result => {
            result = result.data; //取出data这一层
            this.totals = result.totals;
            this.products = result.data;
            this.listLoading = false;
          })
          .catch(result => {
            alert("系统错误！")
          })
    },
    //显示编辑界面
    handleEdit: function (index, row) {
      this.saveForm = Object.assign({}, row); //回显
      console.log(this.saveForm)
      this.title = "编辑";
      this.fileList = [];
      var resources = row.resources;
      if (resources) {
        var resourcesArr = resources.split(",");
        for (var i = 0; i < resourcesArr.length; i++) {
          this.fileList.push({url: "http://123.207.27.208" + resourcesArr[i]})
        }
      }
      this.saveFormVisible = true; // 显示编辑框
    },
    //显示新增界面
    handleAdd: function () {
      this.title = "新增";
      this.saveForm = { //清空
        id: null,
        name: '',
        state: 0,
        resources: null,
        saleprice: null,
        costprice: null,
        productDetail:{  //与后端实体类一致
          intro: '',
          orderNotice: ''
        }
      }
      this.fileList = [];

      this.saveFormVisible = true; //显示新增框
    },
    //保存
    save: function () {
      // 表单上定义了ref="saveForm"
      this.$refs.saveForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认保存吗？', '温馨提示', {}).then(() => {
            this.productLoading = true;
            //拷贝一份新数据
            let para = Object.assign({}, this.saveForm);
            //对数据进行额外处理
            if (para.parent) {
              let arrys = para.parent;//[2,5]
              //后台要的是product对象
              para.parent = {'id': arrys[arrys.length - 1]}
            }
            this.$http.put("/product", para)
                .then(result => {
                  result = result.data
                  //去除忙等框
                  this.productLoading = false;
                  //做提示
                  if (result.success) {
                    this.$message({
                      message: '保存成功',
                      type: 'success'
                    });
                  } else {
                    this.$message({
                      message: result.message,
                      type: 'error'
                    });
                  }
                  //关闭对话框
                  this.saveFormVisible = false;
                  //重新查询数据
                  this.getProducts();
                })
                .catch(result => {
                  alert("系统错误！");
                  this.productLoading = false;
                })
            ;
          });
        }
      });
    },
    //所有选中对象都会传进来
    selsChange: function (sels) {
      this.sels = sels;
      console.log(this.sels)
    },
    //删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '温馨提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        let url = "/product/" + row.id;
        this.$http.delete(url)
            .then(result => {
                  result = result.data; //{sucess:false,message}
                  //去除忙等框
                  this.listLoading = false;

                  if (result.success) {
                    this.page = 1;
                    //提示
                    this.$message({
                      message: '删除成功',
                      type: 'success'
                    });
                    //重新查询数据
                    this.getProducts();
                  } else {
                    //提示
                    this.$message({
                      message: result.message,
                      type: 'error'
                    });
                    //重新查询数据
                    this.getProducts();
                  }
                }
            )
            .catch(result => {
              //去除忙等框
              this.listLoading = false;
              //提示
              this.$message({
                message: '系统错误！',
                type: 'error'
              });
            })

      }).catch(() => {

      });
    },
    //批量删除
    batchRemove: function () {
      var ids = this.sels.map(item => item.id); //[1,2,3]
      console.log(ids);
      this.$confirm('确认删除选中记录吗？', '温馨提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        //传递数组参数
        this.$http.patch("/product", ids)
            .then(result => {
              result = result.data;
              this.listLoading = false;
              if (result.success) {
                this.$message({
                  message: '删除成功',
                  type: 'success'
                });
              } else {
                this.$message({
                  message: result.message,
                  type: 'error'
                });
              }
              this.page = 1; //删除后跳转第一页
              this.getProducts();
            })
            .catch(result => {
              alert("系统错误")
            })
      }).catch(() => {

      });
    },
    handleSuccess(response, file, fileList) {
      if (this.saveForm.resources) {
        // 如果原来有rresource 则在后面拼接
        this.saveForm.resources = this.saveForm.resources + "," + response.resultObj;
      } else {
        this.saveForm.resources = response.resultObj;
      }

      if (this.saveForm.resources) {
        this.fileList = [];
        var arr = this.saveForm.resources.split(",")
        for (var i = 0; i < arr.length; i++) {
          this.fileList.push({url: "http://123.207.27.208" + arr[i]})
        }
      }
    },
    handleRemove(file, fileList) {
      var url = file.url;
      var path = url.substring(url.indexOf("/group"))
      this.$http.delete("/fastdfs?path=" + path).then(res => {
        this.$message.success("删除成功")
      }).catch(res => {
        this.$message.error("删除失败")
      })

      if (this.saveForm.resources) {
        // 分割
        var arr = this.saveForm.resources.split(",")
        for (var i = 0; i < arr.length; i++) {
          if (arr[i] == path) {
            // 从当前下标开始删除 删除一个
            arr.splice(i, 1)
            break;
          }
        }
        // 将数组通过，拼接成字符串
        this.saveForm.resources = arr.join(",")
      }
      // 回显
      // this.fileList = [];
      // if (this.saveForm.resources) {
      //   var arr = this.saveForm.resources.split(",")
      //   for (var i = 0; i < arr.length; i++) {
      //     this.fileList.push({url: "http://123.207.27.208" + arr[i]})
      //   }
      // }
    },
    onsale(){
      var ids = this.sels.map(item => item.id);
      this.$confirm('确认上架嘛？', '提示', {
        type: 'warning'
      }).then(() => {
        if (!ids || ids.length <1){
          this.$message.warning("请选择要上架的宠物！")
          return;
        }
        this.$http.patch("/product/onsale",ids).then(res=>{
          if (res.data.success){
            this.$message.success("上架成功！")
            this.getProducts()
          }else {
            this.$message.error(res.data.message)
          }
        }).catch(res=>{
          this.$message.error("系统繁忙请稍后重试【400.404】！")
        })
      }).catch(() => {
      });
    },
    offsale(){
      var ids = this.sels.map(item => item.id);
      this.$confirm('确认下架吗？', '提示', {
        type: 'warning'
      }).then(() => {
        if (!ids || ids.length <1){
          this.$message.warning("请选择要上架的宠物！")
          return;
        }
        this.$http.patch("/product/offsale",ids).then(res=>{
          if (res.data.success){
            this.$message.success("下架成功！")
            this.getProducts()
          }else {
            this.$message.error("系统繁忙请稍后重试【500】！")
          }
        }).catch(res=>{
          this.$message.error("系统繁忙请稍后重试【400.404】！")
        })
      }).catch(() => {
      });
    }

  },
  mounted() {
    this.getProducts();
  }
}

</script>

<style scoped>

</style>